﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Index;
using Lucene.Net.Analysis;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using System.IO;
using Lucene.Net.Store;
using Lucene.Net.Analysis.Standard;
using System.Data;
using Lucene.Net.Documents;

namespace luceneindex
{
    public class luceneWrapper
    {
        private DataTable dtField = null;

        public string DbConnString { get; set; }

        public string IndexFoldString { get; set; }

        public string LogFilePath { get; set; }

        public string packageName { get; set; }

        public string updateSPName { get; set; }

        private IndexWriter GetIndexWriter(string indexPath, bool isFull)
        {
            return new IndexWriter(new SimpleFSDirectory(new DirectoryInfo(indexPath)), new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30), isFull, IndexWriter.MaxFieldLength.UNLIMITED);
        }

        public void DeleteByTerm(Term term)
        {
            using (IndexWriter indexWriter = this.GetIndexWriter(this.IndexFoldString + @"\", false))
            {
                Analyzer a = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
                QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, term.Field, a);
                Query query = new TermQuery(term);
                query = parser.Parse(term.Text);
                IndexSearcher searcher = new IndexSearcher(new SimpleFSDirectory(new DirectoryInfo(this.IndexFoldString)), true);
                TopScoreDocCollector results = TopScoreDocCollector.Create(searcher.MaxDoc, false);
                searcher.Search(query, results);
                int totalHits = results.TotalHits;
                Console.WriteLine(string.Format("now there are {0} index files found", totalHits));
                indexWriter.Optimize();
            }
        }

        public void FullIndexing()
        {
            this.CreateIndex(true);
        }

        public void IncIndexing()
        {
            this.CreateIndex(false);
        }

        private void CreateIndex(bool isFull)
        {
            string path = this.IndexFoldString + @"\";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }

            using (

            IndexWriter indexWriter = this.GetIndexWriter(path, isFull))
            {
                if (!isFull)
                {
                    indexWriter.MergeFactor = 30;
                }
               
                if (isFull)
                {
                    this.IndexDocs(indexWriter);
                }
                else
                {
                    this.IndexIncDocs(indexWriter);
                }
            }
        }

        private void IndexDocs(IndexWriter writer)
        {
            DataSet dataSet = new DataSet();
            DateTime now = DateTime.Now;
            if ((dataSet.Tables[0] != null) && (dataSet.Tables[1] != null))
            {
                DataTable table = dataSet.Tables[0];
                dataSet = null;
                foreach (DataRow row in table.Rows)
                {
                    writer.AddDocument(this.IndexDocument(row));
                }
            }
        }

        private void IndexIncDocs(IndexWriter writer)
        {
            DataTable dt = new DataTable();
            foreach (DataRow row in dt.Rows)
            {
                writer.AddDocument(this.IndexDocument(row));
            }
        }

        private Document IndexDocument(DataRow dr)
        {
            Document document = new Document();
            foreach (DataRow row in this.dtField.Rows)
            {
                string name = row.Field<string>("COLUMN_NAME");
                string str2 = row.Field<string>("TOKENIZED");
                if (str2 != null)
                {
                    if (!(str2 == "Y"))
                    {
                        if (str2 == "N")
                        {
                            goto Label_012F;
                        }
                    }
                    else
                    {
                        Field field = new Field(name, dr[name].ToString().Trim(), Field.Store.YES, Field.Index.ANALYZED);
                        if (row["BOOST_VALUE"].ToString() != "")
                        {
                            field.Boost = Convert.ToSingle(row["BOOST_VALUE"]);
                        }
                        document.Add(field);
                        if (row["FACET_FLAG"].ToString() == "Y")
                        {
                            document.Add(new Field(name + "_FACET", dr[name].ToString().Trim(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                        }
                    }
                }
                goto Label_01B0;
            Label_012F:
                document.Add(new Field(name, dr[name].ToString().Trim(), Field.Store.YES, Field.Index.ANALYZED));
                if (row["FACET_FLAG"].ToString() == "Y")
                {
                    document.Add(new Field(name + "_FACET", dr[name].ToString().Trim(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                }
            Label_01B0: ;
            }
            return document;
        }
    }
}
